package com.iespring.service.app.coupon;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iespring.bean.admin.promotion.po.MallCoupon;
import com.iespring.bean.admin.promotion.po.MallCouponUser;
import com.iespring.bean.admin.user.entity.MallUser;
import com.iespring.bean.app.cart.vo.CartIndexGoodsInfoVo;
import com.iespring.bean.app.coupon.bo.WxCouponPageBo;
import com.iespring.bean.app.coupon.vo.WxCouponListVo;
import com.iespring.bean.app.coupon.vo.WxCouponPageVo;
import com.iespring.bean.common.BaseRespVo;
import com.iespring.bean.common.CommonData;
import com.iespring.mapper.admin.MallCouponMapper;
import com.iespring.mapper.admin.MallCouponUserMapper;
import com.iespring.mapper.app.WxCartMapper;
import com.iespring.util.UserInfoUtils;
import com.iespring.util.map.CartIdListUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Auth: 杨宇健
 * Time: 2023/1/1 18:55
 * Description: 优惠券service
 **/
@Service
public class WxCouponServiceImpl implements WxCouponService {
    @Resource
    MallCouponMapper mallCouponMapper;

    @Resource
    MallCouponUserMapper mallCouponUserMapper;

    @Resource
    WxCartMapper wxCartMapper;

    @Resource
    CartIdListUtils cartIdListUtils;

    @Override
    public BaseRespVo myList(WxCouponPageBo pageInfo) {
        MallUser user = UserInfoUtils.getUser();

        Integer userId = user.getId();
        pageInfo.setUserId(userId);

        PageHelper.startPage(pageInfo.getPage(), pageInfo.getLimit());
        List<WxCouponPageVo> pageInfoList = mallCouponUserMapper.selectUserConpon(pageInfo);
        PageInfo pageInfoData = new PageInfo(pageInfoList);
        pageInfoList.stream().forEach( vo -> {
            vo.setAvailable(false);
        });
        return BaseRespVo.ok(CommonData.data(pageInfoData));
    }

    @Override
    public BaseRespVo list(WxCouponPageBo pageInfo) {
        MallCoupon mallCoupon = new MallCoupon();
        mallCoupon.setType((short) 0);
        mallCoupon.setStatus((short) 0);
        PageHelper.startPage(pageInfo.getPage(), pageInfo.getLimit());
        List<MallCoupon> pageInfoList = mallCouponMapper.selectByMallCoupon(mallCoupon);
        PageInfo pageInfoData = new PageInfo(pageInfoList);
        List<WxCouponListVo> voList = pageInfoList.stream().map(list -> {
            WxCouponListVo vo = new WxCouponListVo();
            BeanUtils.copyProperties(list, vo);
            return vo;
        }).collect(Collectors.toList());
        //CommonData<WxCouponListVo> commonData = new CommonData<>();
        //commonData.setList(voList);
        CommonData data = CommonData.data(pageInfoData);
        data.setList(voList);
        return BaseRespVo.ok(data);

    }

    @Transactional
    @Override
    public BaseRespVo receive(Integer couponId) {
        MallCoupon coupon = mallCouponMapper.selectByPrimaryKey(couponId);
        //type '优惠券赠送类型，如果是0则通用券，用户领取；如果是1，则是注册赠券；如果是2，则是优惠券码兑换；',
        //status '优惠券状态，如果是0则是正常可用；如果是1则是过期; 如果是2则是下架。',
        if (coupon.getType() == 2 || coupon.getStatus() != 0) {
            return BaseRespVo.error("优惠券状态不对，无法领取", 501);
        }
        //type 1 判断是否已领取本优惠券

        return InsertCoupon(coupon);
    }

    @Transactional
    @Override
    public BaseRespVo exchange(String code) {
        MallCoupon mallCoupon = new MallCoupon();
        mallCoupon.setCode(code);
        mallCoupon.setDeleted(false);


        List<MallCoupon> coupons = mallCouponMapper.selectByMallCoupon(mallCoupon);
        //type '优惠券赠送类型，如果是0则通用券，用户领取；如果是1，则是注册赠券；如果是2，则是优惠券码兑换；',
        //status '优惠券状态，如果是0则是正常可用；如果是1则是过期; 如果是2则是下架。',
        if (coupons.size() < 0) {
            return BaseRespVo.error("兑换码错误，无法领取哦", 502);
        }
        MallCoupon coupon = coupons.get(0);
        if (coupon.getStatus() != 0) {
            return BaseRespVo.error("优惠券状态不对，无法领取", 501);
        }

        return InsertCoupon(coupon);
    }

    @Override
    public BaseRespVo selectList(Integer cartId, Integer grouponRulesId) {
        // 获得用户的所有未使用的优惠券
        MallCouponUser mallCouponUser = new MallCouponUser();
        mallCouponUser.setUserId(UserInfoUtils.getUser().getId());
        mallCouponUser.setStatus((short) 0);
        mallCouponUser.setDeleted(false);
        List<MallCouponUser> mallCouponUserList = mallCouponUserMapper.selectByMallCouponUser(mallCouponUser);
        //无优惠券可用
        if (mallCouponUserList.size() == 0) {
            CommonData<WxCouponPageVo> commonData = new CommonData<>();
            commonData.setTotal(0);
            commonData.setLimit(0);
            commonData.setPage(1);
            commonData.setPages(1);
            return BaseRespVo.ok();
        }
        //获得对应的优惠券列表
        List<Integer> couponIdList = mallCouponUserList.stream().map(couponUser -> {
            Integer couponId = couponUser.getCouponId();
            return couponId;
        }).collect(Collectors.toList());
        // 获得cartId对应的商品价格

        //ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //
        //HttpSession session = sra.getRequest().getSession();
        //Object cartIdList = session.getAttribute("cartIdList");

        List<Integer> cartIdList = cartIdListUtils.getCartIdList();

        // session.setAttribute("user", []);
        List<Integer> cartIds = new ArrayList<>();


        if (cartId == 0) {
            if (cartIdList != null) {
                cartIds = (List<Integer>) cartIdList;
                if (cartIds.size() == 0 || cartIdList.get(0) == -1) {
                    return BaseRespVo.error("cartId为0且用户并未选中任何购物车", 400);
                }

            }else {
                return BaseRespVo.error("cartId为0且用户并未选中任何购物车", 400);
            }

        }else {
            //默认cartId, 如果cartId不为0，那结果就是传进来的cartId, 如 [cartId]
            cartIds.add(cartId);
        }


        List<CartIndexGoodsInfoVo> cartBySql = wxCartMapper.getCartGoodsListByIdList(cartIds);

        // 购物车总价
        BigDecimal sumPrice = new BigDecimal(0);
        //cartBySql.stream().forEach( cart -> {
        //    BigDecimal price = cart.getPrice();
        //    Short number = cart.getNumber();
        //    BigDecimal sumPriceInCircle = price.multiply(new BigDecimal(number));
        //    sumPrice = sumPrice.add(sumPriceInCircle);
        //});
        // 购物车循环相加
        for (CartIndexGoodsInfoVo cart : cartBySql) {
            BigDecimal price = cart.getPrice();
            Short number = cart.getNumber();
            BigDecimal sumPriceInCircle = price.multiply(new BigDecimal(number));
            sumPrice = sumPrice.add(sumPriceInCircle);
        }



        //借助分页插件快速获得页码信息
        PageHelper.startPage(1, 10000000);
        List<MallCoupon> coupons= mallCouponMapper.selectByIdList(couponIdList);
        PageInfo pageInfo = new PageInfo(coupons);
        //将用于返回的数据，先将页码信息复制给data, list会被替换
        CommonData data = CommonData.data(pageInfo);

        //将List<MallCoupon> 转为 List
        BigDecimal finalSumPrice = sumPrice;
        List<WxCouponPageVo> couponVoList = coupons.stream().map(coupon -> {
            WxCouponPageVo couponVo = new WxCouponPageVo();
            BeanUtils.copyProperties(coupon, couponVo);
            BigDecimal minPrive = couponVo.getMin();
            //min比大于等于总价sumPrice可用就是true，否则是false
            couponVo.setAvailable(finalSumPrice.compareTo(minPrive) >= 0 ? true : false);
            return couponVo;
        }).collect(Collectors.toList());

        //TODO goods_Type 和团购信息没用上
        data.setLimit(couponVoList.size());
        data.setList(couponVoList);
        return BaseRespVo.ok(data);

        //List<MallCoupon> coupons = mallCouponMapper.selectByMallCoupon(mallCoupon);
    }

    //生成用户的优惠券
    private BaseRespVo InsertCoupon(MallCoupon coupon) {


        if (coupon.getLimit() == 1) {
            MallCouponUser mallCouponUser = new MallCouponUser();
            mallCouponUser.setUserId(UserInfoUtils.getUser().getId());
            mallCouponUser.setDeleted(false);
            List<MallCouponUser> couponUserListList = mallCouponUserMapper.selectByMallCouponUser(mallCouponUser);
            if (couponUserListList.size() > 0) {
                return BaseRespVo.error("您已领取过本优惠券，无法领取哦", 501);
            }
        }

        MallCouponUser mallCouponUser = new MallCouponUser();
        mallCouponUser.setCouponId(coupon.getId());
        Date date = new Date();
        mallCouponUser.setAddTime(date);
        mallCouponUser.setUpdateTime(date);
        //timeType '有效时间限制，如果是0，则基于领取时间的有效天数days；如果是1，则start_time和end_time是优惠券有
        //timeType 0 结束时间为现在 + 天数
        if (coupon.getTimeType() == 0) {
            mallCouponUser.setStartTime(date);
            mallCouponUser.setEndTime(new Date(date.getTime() + coupon.getDays() * 24 * 3600 * 1000));
        }
        //timeType 1 则是优惠券本身的结束时间
        mallCouponUser.setStartTime(coupon.getStartTime());
        mallCouponUser.setEndTime(coupon.getEndTime());
        mallCouponUser.setUserId(UserInfoUtils.getUser().getId());
        mallCouponUser.setStatus((short) 0);
        mallCouponUser.setDeleted(false);

        //优惠券数量不够
        if (coupon.getTotal() < 0) {
            return BaseRespVo.error("优惠券已被领取完毕了哦！请等待下次", 502 );

        }
        if (coupon.getTotal() > 0){
            //如果剩余数量为1则减去2，因为剩余数量为0代表不限量，要设置为负数才算真正的归零
            int reduction = coupon.getTotal() == 1? 2: 1;
            coupon.setTotal( coupon.getTotal() - reduction);

        }
        //更新优惠券数量
        mallCouponMapper.updateByPrimaryKey(coupon);
        //给用户优惠券
        mallCouponUserMapper.insert(mallCouponUser);
        return BaseRespVo.ok();
    }
}
